<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Bill\Controllers;


use App\Eloquent\Ygt\BillLog;
use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\Warehouse;
use App\Eloquent\Ygt\WarehouseBill;
use App\Eloquent\Ygt\WarehouseBillRelation;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class CustomerController extends Controller
{
    public $userId          = 25;
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $type               = request('type',2);//0：未结清,1：已结清客户,2：全部客户
        $page               = request( 'page', 1 );
        $limit              = request('limit', 10 );
        $offset             = ($page - 1) * $limit;
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId];
        if($type == 1)
        {
            $where['status']    = 1;
        }
        else if($type == 0){
            $where['status']    = 0;
        }
        $fields             = 'customer_id,sum(now_money) as now_money_sum';
        $orderby            = 'now_money_sum';
        $groupby            = 'customer_id';
        $object             = WarehouseBill::where($where)->selectRaw($fields)->groupBy($groupby);
        if($type ==1){
            $object = $object->having('now_money_sum','=',0);
        }
        else if($type == 0){
            $object = $object->having('now_money_sum','>',0);
        }
        $customerData       = $object->limit($limit+1)->offset($offset)->orderByDesc($orderby)->get()->toArray();
        //统计获得的数据总数
        $count              =count($customerData);
        //剔除最后一条数据
        if($count > $limit){
            array_pop($customerData);
        }

        $listData = [];
        $customerIdArr      = [];
        foreach($customerData as $key=>$val)
        {
            $customerIdArr[]=$val['customer_id'];

            $temp['id'] = $val['customer_id'];
            $temp['img_path']  = '';
            $temp['last_money_text']  = '';
            $temp['last_order_text']  = '';
            $temp['income_money']     = $val['now_money_sum'];
            $temp['status']     = 0;
            $listData[$val['customer_id']] = $temp;
        }

        if(!empty($customerIdArr))
        {
            //取头像和名字
            $where              = ['id'=>['in',$customerIdArr]];
            $fields             = 'ygt_customer.id,ygt_customer.customer_name,ygt_customer.avatars_id';
            $customerList       = Customer::getList($where,$fields)->toArray();
            foreach($customerList as $key=>$val)
            {
                $imgPath            = Func::getImgUrlById($val['avatars_id']);
                $listData[$val['id']]['img_path'] = $imgPath;
                $listData[$val['id']]['customer_name'] = $val['customer_name'];
            }
            //取最近收款
            $billLogList        = BillLog::whereIn('id',
                    //BillLog::whereIn('customer_id',$customerIdArr)->selectRaw(' MAX(id) as id')->groupBy('customer_id')
                    function($query) use($customerIdArr){
                        $query->from((new BillLog())->getTable())->whereIn('customer_id',$customerIdArr)->selectRaw('MAX(id) as id')->groupBy('customer_id');
                    }
                )->get()->toArray();
            foreach($billLogList as $key=>$val)
            {
                $money          = $val['money'];
                $ymd            = date('Y-m-d',$val['created_at']);
                $text           = $ymd.','.$money.'元';
                $listData[$val['customer_id']]['last_money_text'] = $text;
            }

            //取最近订单
            $orderList          = Order::whereIn('id',
                    function($query) use($customerIdArr){
                        $query->from((new Order())->getTable())->WhereIn('customer_name',$customerIdArr)->selectRaw('MAX(id) as id')->groupBy('customer_name');
                    }
                )
                ->get()->toArray();
            foreach($orderList as $key=>$val)
            {
                $number         = $val['product_num'];
                $number         = str_replace(',','',$number);
                $ymd            = date('Y-m-d',$val['created_at']);
                $text           = $ymd.','.$number;
                $listData[$val['customer_name']]['last_order_text'] = $text;
            }
        }

        $listData = array_values($listData);

        $where              = ['company_id'=>$companyId,'status'=>0];
        $totalMoney         = WarehouseBill::where($where)->sum('now_money');

        $data               = [
            'lists'=>$listData,'total_money'=>sprintf('%.2f',$totalMoney)
        ];
        $pagingData         = [
            'page'         => $page,
            'pageSize'     => $limit,
            'total'         => $offset+$count,
            'total_page'   => ceil(($offset+$count)/$limit),
            'keyword'      => ''
        ];
        return $this->pagingData($data, $pagingData);
    }
    public function billList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $page               = request( 'page', 1 );
        $limit              = request('limit', 10 );

        $type               = request('type',1);//0:未结清 1:已结清客户,2全部客户
        $customer_id        = request('customer_id',0);//账单涉及用户id

        $type               = request('type',1);//已结清客户,2全部客户
        $customerId             = request('customer_id',0);

        $offset             = ($page - 1) * $limit;
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
//        $billList           = WarehouseBill::getCustomerBillList($companyId,$type,$limit+1,$offset,$customer_id);
//        $count              = count($billList);
//
//        //剔除最后一条数据
//        if($count > $limit){
//            array_pop($billList);
//        }

        $billList           = WarehouseBill::getCustomerBillList($companyId,$type,$limit,$offset,$customerId);
        $where              = ['company_id'=>$companyId, 'status'=>$type];
        $count              = WarehouseBill::getCustomerBillListCount($companyId,$type,$customerId);

        $warehousBillIdArr  = [];
        foreach($billList as $key=>$val)
        {
            $warehousBillIdArr[]    = $val['id'];
        }
        $relationList       = WarehouseBillRelation::getListByWarehouseBillIdArr($warehousBillIdArr);
        $imgList            = [];
        foreach($relationList as $key=>$val)
        {
            $warehouseBillId    = $val['warehouse_bill_id'];
            $imgPath            = $val['img_path'];
            if(!empty($imgPath))
            {
                $imgList[$warehouseBillId][]    = $imgPath;
            }
        }

        $totalMoney = 0;
        foreach($billList as $key=>$val)
        {
            $valId          = $val['id'];
            $imgArr         = [];
            if(isset($imgList[$valId]))
            {
                $imgArr     = $imgList[$valId];
            }
            $billList[$key]['img_arr']  = $imgArr;
            $billList[$key]['pre_money']  = 0;
        }
        $where              = ['company_id'=>$companyId,'status'=>0];
        if($customer_id){
            $where['customer_id'] = $customer_id;
        }
        $totalMoney         = WarehouseBill::where($where)->sum('now_money');

        $data               = [
            'lists'=>$billList,'total_money'=>$totalMoney
        ];
        $pagingData         = [
            'page'         => $page,
            'pageSize'     => $limit,
//            'total'         => $count+$offset,
//            'total_page'   => ceil(($offset+$count)/$limit),
            'total'         => $count,
            'total_page'   => ceil(($count)/$limit),
            'keyword'      => ''
        ];
        return $this->pagingData($data, $pagingData);
    }
    public function moneyList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $tableId            = request( 'id', 0 );
        if( !$userInfo || !$tableId )
        {
            xThrow( ERR_PARAMETER );
        }
//        $where              = [
//            'ygt_bill_log.type'=>4,
//            'ygt_bill_log.table'=>'warehouse_bill',
//            'ygt_bill_log.table_id'=>$tableId
//        ];

        //转换tableId
        $warehouseBillId = $tableId;
        $tmpWarehouseBillMoneyRow = \App\Eloquent\Ygt\WarehouseBillMoney::where(['warehouse_bill_id'=>$warehouseBillId])->first();
        if($tmpWarehouseBillMoneyRow){
            $tableId = $tmpWarehouseBillMoneyRow['id'];
        }

        $where              = [
            'ygt_bill_log.type'=>1,
            'ygt_bill_log.table'=>'ygt_warehouse_bill_money',
            'ygt_bill_log.table_id'=>$tableId
        ];
        $limit              = $offset = '';
        $lists              = BillLog::getListDetail($where,$limit,$offset);
        return $lists;
    }
    public function orderList()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $warehouseBillId    = request( 'id', 0 );
        if( !$userInfo || !$warehouseBillId )
        {
            xThrow( ERR_PARAMETER );
        }
        $where              = ['warehouse_bill_id'=>$warehouseBillId];
        $relationList       = WarehouseBillRelation::getList($where)->toArray();
        $warehouseIdArr     = $numberArr = [];
        foreach($relationList as $key=>$val)
        {
            $valWarehouseId         = $val['warehouse_id'];
            $valNumber              = $val['number'];
            $warehouseIdArr[]       = $val['warehouse_id'];
            $numberArr[$valWarehouseId] = $valNumber;
        }
        $tableviewSource            = [];
        if(!empty($warehouseIdArr))
        {
            $where                  = ['id'=>['in',$warehouseIdArr]];
            $warehouseList          = Warehouse::getList($where)->toArray();
            foreach($warehouseList as $key=>$val)
            {
                $valId              = $val['id'];
                $valOrderId         = $val['order_id'];
                $number             = isset($numberArr[$valId]) ? $numberArr[$valId] : 0;
                $order              = Order::where('id',$valOrderId)->first();
                $orderTitle         = '';
                if($order)
                {
                    $orderTitle     = $order->order_title;
                }
                $temp               = [
                    'ordertype_title' => '工艺:',
                    'order_title' => '单号:',
                    'unit_name' => $val['field_name_23'],
                    'product_name' => $val['product_name'],
                    'order_title_value' => $orderTitle,
                    'firstPropertyName' => '成品规格',
                    'secondPropertyName' => '数量',
                    'thirdPropertyName' => '交货日期',
                    'thirdPropertyValue' => $val['finished_date'],
                    'secondPropertyValue' => $number,
                    'firstPropertyValue' => $val['finished_specification'],
                    'productionCaseDiagram' => $val['img_path'],
                    'productOrderTimeValue' => '',
                    'orderTypeTitle' => $val['order_type_title'],
                    'relate_id' => 0,
                    'orderStatus' => '',
                    'statusColor' => 'FFB401',
                ];
                $tableviewSource[]      = $temp;
            }
        }
        $result             = [
            'pageID'=>0,
            'data'=>['tableviewSource'=>$tableviewSource]
        ];
        return $result;
    }
}